package org.struts.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.struts.action.Action;
import org.struts.bean.XmlBean;
import org.struts.form.ActionForm;
import org.struts.util.FullBean;

public class ActionServlet extends HttpServlet {
	private static final String CONFIGLOCATION="configLocation";
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		   //1,获取请求路径
		      String path = req.getRequestURI().substring(req.getRequestURI().lastIndexOf("/")+1, req.getRequestURI().lastIndexOf(".action"));
		   // 2,获取路径所对应的XmlBean;
		      Map<String,XmlBean>map= (Map<String, XmlBean>) req.getSession().getServletContext().getAttribute(CONFIGLOCATION);
		     XmlBean bean = map.get(path);
		    //3,封装客户端的请求数据
		   ActionForm form =FullBean.full(req,bean.getFormClass());
		    //4,调用相应的Action
		   Action action =null;
		   try {
			action= (Action) Class.forName(bean.getType()).newInstance();
			String url = action.execute(req, resp,form);
			String forward =bean.getResultMap().get(url);
			//5,转发到相应的页面
			req.getRequestDispatcher(forward).forward(req, resp);
		} catch (Exception e) {
			throw new RuntimeException("action 解析失败！！！",e);
		}
	}
       
}
